<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="formConfig.rules"
    :label-width="formConfig.labelWidth"
    class="form"
  >
    <el-row>
      <template v-for="item in formConfig.formItems" :key="item.field">
        <el-col :span="item.span ?? 24">
          <el-form-item v-if="item.type === 'input' || item.type === 'password'" :label="item.label" :prop="item.prop">
            <el-input v-model="form[`${item.field}`]" style="width: 100%" v-bind="item.otherOptions" />
          </el-form-item>
          <el-form-item  v-else-if="item.type === 'select'" :label="item.label" :prop="item.prop">
            <el-select style="width: 100%" v-model="form[`${item.field}`]" v-bind="item.otherOptions">
              <el-option
                v-for="option in item.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
    </el-row>
    <el-row v-if="formConfig.btns">
      <el-form-item style="width: 100%">
        <div class="btns">
          <el-button v-for="btn in formConfig.btns" :key="btn.name" @click="sendAction(btn.action, btn.needValid)">{{btn.name}}</el-button>
        </div>
      </el-form-item>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, inject } from 'vue'
import type { PropType } from 'vue'
import type { FormInstance } from 'element-plus'
import { IForm, IMsg } from './type'

import { sendMsgKey } from '@/utils/send-msg-key'

const props = defineProps({
  formConfig: {
    type: Object as PropType<IForm>,
    required: true
  }
})

const sendMsg = inject(sendMsgKey)

const formRef = ref<FormInstance>()
const form: any = reactive({})
for (const item of props.formConfig.formItems) {
  console.log(item.field)
  form[`${item.field}`] = ''
}

// 表单按钮行为
const sendAction = async (action: string, needValid: boolean) => {
  // 定义发送出去的消息
  const msg: IMsg = {
    action: action,
    data: form
  }
  if (needValid) {
    formRef.value!.validate((valid, fields) => {
      if (valid) {
        // 把事件的名称使用 provide/inject 通信，在父组件中直接使用定义好的事件名称即可
        sendMsg?.(msg)
      } else {
        console.log('error submit')
      }
    })
  } else {
    sendMsg?.(msg)
  }
}

// 获取表单数据
const getFormData = () => { return form }

// 重置表单
const resetFields = (formRef: FormInstance | undefined) => {
  if (!formRef) return
  formRef.resetFields()
}

defineExpose({
  getFormData,
  resetFields
})
</script>

<style lang="less" scoped>
.form {
  padding: 10px;
  .btns {
    margin: 0 auto;
    .el-button {
      background: #ecf5ff;
      color: #888;
      width: 100px;
    }
  }
}
</style>
